<template>
  <MenuPage
    :columns="tableCol"
    :data="tableData"
    :page.sync="queryObj.page"
    :size.sync="queryObj.rows"
    :total="total"
    :loading="loadingTbale"
    @queryFun="getQueryList"
  >
    <template slot="search">
      <!-- <Button type="primary" ghost @click="showKnowLedgeCompetModel($event, 'add')" icon="md-add"
        >创建{{ pageTitle }}</Button
      > -->
      <!-- <Divider type="vertical" /> -->
      <Checkbox v-model="createByMe" @on-change="getQueryListPage(1)">我创建的</Checkbox>
      <Select filterable
        clearable
        placeholder="竞赛进度"
        v-model="queryObj.progress"
        filterable
        style="width: 150px; margin-left: 15px"
        @on-change="getQueryListPage(1)"
      >
        <Option :value="0">准备中</Option>
        <Option :value="2">进行中</Option>
        <Option :value="4">已结束</Option>
      </Select>
      <Input
        v-model.trim="queryObj.contestName"
        placeholder="名称"
        style="width: 200px;margin-left:16px"
        clearable
        @on-change="getDataBounce"
      />
      <Button type="primary" ghost class="md-add-jh" @click="showKnowLedgeCompetModel($event, 'add')">
        <i class="el-icon-edit"></i>
        创建
      </Button>
        <Button
        style="height: 32px; margin-left: 5px"
        ghost
        type="primary"
        @click="refreshSceneList"
        ><i class="el-icon-refresh-right"
      /></Button>
      <!-- <Button
        class="header-btn"
        type="primary"
        ghost
        style="height: 32px;margin-left: 5px;"
        @click="refreshSceneList"
        ><Icon size="16" type="ios-refresh"
      /></Button> -->
    </template>
    <knowledge-model
      ref="knowledgeModels"
      @getList="getQueryList"
      @refreshSceneList="refreshSceneList"
    ></knowledge-model>
  </MenuPage>
</template>

<script>
import encryption from '@/libs/encryption.js'
import usally from '@/mixin/usally'
import knowledgeModel from './knowledgeModel'
import { compitionlist, delcompetition, releaseKnowledgeGrade } from '@/api/competition'
import { sceneFiling, getFilingList } from '@/api/drill_compete.js'
import { mapActions, mapGetters, mapState } from 'vuex'
import { debounce, parseJson } from '@/libs/utils'

export default {
  name: 'mains',
  components: {
    knowledgeModel
  },
  mixins: [usally],
  data() {
    let September = sessionStorage.getItem('November')
    September = JSON.parse(encryption.SelfUseDecrypt(September))
    return {
      loadingTbale: true,
      USER_ID: September.userId,
      USER_Name: September.nickname,
      isRootDesigner: September.isRootDesigner,
      reportCol: [
        {
          key: 'rank',
          title: '排名'
        },
        {
          key: 'userName',
          title: '用户名称'
        },
        {
          key: 'totalScore',
          title: '总分'
        },
        {
          key: 'bestCategory',
          title: '最擅长的题目类型'
        }
      ],
      compReportInfo: {},
      queryObj: {
        page: 1,
        rows: 10,
        matchMode: '3',
        createUserId: September.userId,
        contestName: ''
      },
      createByMe: false,
      tableCol: [
        {
          title: '名称',
          key: 'contestName',
          placement: 'top-left',
          width: 300,
          render: (h, params) => {
            return h(
              'Tooltip',
              {
                props: {
                  width: 400,
                  transfer: true,
                  placement: 'top-start'
                }
              },
              [
                h(
                  'a',
                  {
                    class: 'text-ellipsis',
                    style: {
                      marginRight: '5px',
                      maxWidth: '300px'
                    },
                    on: {
                      click: () => {
                        this.$router.push({
                          path: '/kcContestDetail',
                          query: {
                            name: params.row.contestName,
                            id: params.row.id,
                            page: this.queryObj.page
                          }
                        })
                        // let query = {
                        //   name: params.row.contestName,
                        //   id: params.row.id
                        // }
                      }
                    }
                  },
                  params.row.contestName
                ),
                h(
                  'div',
                  {
                    slot: 'content',
                    style: {
                      'white-apace': 'normal',
                      'word-break': 'break-all'
                    }
                  },
                  params.row.contestName
                )
              ]
            )
          }
        },
        {
          title: '竞赛进度',
          key: 'activityStatus',
          placement: 'top-right',
          render: (h, params) => {
            return h(
              'span',
              {
                style: {
                  color: this.statusFilter(params.row.activityStatus).color
                }
              },
              this.statusFilter(params.row.activityStatus).txt
            )
          }
        },
        {
          title: '是否立即显示成绩',
          key: 'needRelease',
          width: 50,
          render: (h, params) => {
            let extension = parseJson(params.row.extension)
            return h('span', extension.needRelease === 0 ? '否' : '是')
          }
        },
        {
          type: 'status',
          title: '归档状态',
          key: 'filingStatus',
          placement: 'top-right',
          show: () => {
            return this.hasFile
          },
          render: (h, params) => {
            return h(
              'span',
              {
                style: {
                  color: params.row.filingStatus ? 'var(--status-yes)' : 'var(--status-no)'
                }
              },
              params.row.filingStatus ? '已归档' : '未归档'
            )
          }
        },
        {
          title: '开始时间',
          key: 'startTime',
          width: 170
        },
        {
          title: '结束时间',
          key: 'endTime',
          width: 170
        },
        {
          title: '创建者',
          key: 'createUser',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 148
        },
        {
          title: '操作',
          placement: 'top-right',
          action: true,
          key: 'action',
          width: 240,
          opList: [
            {
              txt: '发布成绩',
              disabled: (data) => {
                let extension = parseJson(data.extension)
                return (
                  data.createUserId != this.USER_ID ||
                  data.activityStatus != '2' ||
                  extension.needRelease !== 0 ||
                  extension.status === 1
                )
              },
              on: {
                click: (data, e) => {
                  this.publishScore(data)
                }
              }
            },
            {
              txt: '修改',
              disabled: (data) => {
                return data.activityStatus !== '0' || data.createUserId !== this.USER_ID
              },
              fun: (data) => {
                this.showKnowLedgeCompetModel(data, 'modify')
              }
            },
            {
              txt: '删除',
              type: 'delete',
              tooltip: true,
              title: '你确定要删除吗?',
              disabled: (data) => {
                return data.activityStatus === '1' || data.createUserId !== this.USER_ID
              },
              fun: this.delListItem
            },
            {
              txt: '归档',
              tooltip: true,
              title: '你确定要归档吗?',
              show: () => {
                return this.hasFile
              },
              disabled: (data) => {
                return data.activityStatus == 2 &&
                  !data.filingStatus &&
                  data.createUserId === this.USER_ID
                  ? false
                  : true
              },
              fun: this.scenefiling
            }
          ]
        }
      ],
      tableData: [],
      total: 0,
      showModel: false,
      timeout: null
    }
  },
  watch: {
    hasFile: {
      //初始化的时候执行一次
      immediate: true,
      handler(val) {
        if (val) {
        }
      }
    }
  },
  mounted() {
    // 计算分页大小后，获取知识赛列表
    // this.setStyle();
    // window.addEventListener('resize', this.setStyle);
    // 获取题目方向，往vuex与session storage中各放置了一份备份
    this.getAllPoints()
    this.getQueryList()
  },
  beforeDestroy() {
    clearTimeout(this.timeout)
    clearTimeout(this.timer)
    // window.removeEventListener('resize', this.setStyle)
  },
  computed: {
    ...mapGetters('compet', ['passParams']),
    ...mapState('compet', ['hasFile']),
    pageTitle() {
      //当前菜单显示名
      return this.$store.getters.pageTitle
    }
  },
  methods: {
    publishScore(item) {
      let { id, extension } = item
      let obj = parseJson(extension)
      obj.status = 1
      extension = JSON.stringify(obj)
      releaseKnowledgeGrade({
        id,
        extension
      })
        .then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.$Message.success('发布成绩成功')
          this.getQueryList()
        })
        .catch(() => {
          this.$Message.error('发布成绩异常')
        })
    },
    // 根据页面高度实时计算分页大小并获取首页数据
    // setStyle() {
    //   clearTimeout(this.timeout)
    //   this.timeout = setTimeout(() => {
    //     window.fullHeight = document.documentElement.clientHeight
    //     window.fullWidth = document.documentElement.clientWidth
    //     this.fullHeight = window.fullHeight
    //     this.fullWidth = window.fullWidth
    //     this.setTableHei = this.fullHeight - 197
    //     this.queryObj.page = 1
    //     this.queryObj.rows = Math.floor(this.setTableHei / 96) || 1
    //     this.getQueryList()
    //   }, 200)
    // },
    // 获取知识赛列表，同步获取归档状态
    getQueryList() {
      this.loadingTbale = true
      this.$nextTick(() => {
        let params = { ...this.queryObj }
        params.createUserId = this.createByMe ? this.USER_ID : ''
        compitionlist(params).then((data) => {
          if (data.code == 1) {
            let tableData = data.attribute.dataList
            this.total = data.attribute.totalCount
            let statusArr = this.tableData.map((item) => item.activityStatus)
            let pArr = tableData.map(async (item) => {
              let status = await this.getFilingStatus(item)
              item.filingStatus = status
            })
            Promise.all(pArr)
              .then(() => {
                this.tableData = tableData
              })
              .finally(() => {
                this.loadingTbale = false
              })
            clearTimeout(this.timeout)
            if (statusArr.some((status) => status != '2')) {
              // 这个status的状态暂时意义不明，不清楚是在什么情况下需要定时刷新列表
              this.timeout = setTimeout(() => {
                this.getQueryList()
              }, 10000)
            }
          } else {
            this.$Message.error(data.message)
          }
        })
      })
    },
    // 查询归档状态，有归档数据返回1，没有归档状态返回0
    getFilingStatus(sceneInfo) {
      return new Promise((resolve) => {
        let params = {
          pageIndex: 1,
          pageSize: 10,
          sceneId: sceneInfo.id
        }
        getFilingList(params).then((data) => {
          if (data.code == 1 && data.data.items.length > 0) {
            resolve(1)
          } else {
            resolve(0)
          }
        })
      })
    },
    // 打开新建、修改知识赛的模态框
    showKnowLedgeCompetModel(passObj, type) {
      if (type === 'modify') {
        this.$refs.knowledgeModels.openModel(passObj)
      } else {
        this.$refs.knowledgeModels.openModel()
      }
    },
    // 防抖封装，竞赛名称改变时，延迟更新列表数据
    getDataBounce: debounce(function() {
      this.getQueryListPage(1)
    }),
    // 修改当前页并查询
    getQueryListPage(page) {
      this.queryObj.page = page
      this.getQueryList()
    },
    // 修改分页大小并查询
    getQueryListPageSize(pageSize) {
      this.queryObj.rows = pageSize
      this.getQueryList()
    },
    // 重置查询条件并查询
    refreshSceneList() {
      this.queryObj = Object.assign(this.queryObj, {
        page: 1,
        matchMode: '3',
        createUserId: this.USER_ID,
        contestName: '',
        progress: ''
      })
      this.createByMe = false
      this.getQueryList()
    },
    // 删除知识赛
    delListItem(delObj) {
      delcompetition(delObj.id).then((data) => {
        if (data.code == 1) {
          this.$Message.info('删除竞赛成功')
          this.getQueryList()
        } else {
          this.$Message.error(data.message)
        }
      })
    },
    ...mapActions('compet', ['getAllPoints']),
    // 归档知识赛
    scenefiling(sceneInfo) {
      sceneFiling(sceneInfo.id)
        .then((data) => {
          if (data.code == 1) {
            this.$Message.info('场景信息归档成功')
            this.getQueryList()
          } else {
            this.$Message.error('场景信息归档失败')
          }
        })
        .catch(() => {
          this.$Message.error('场景信息归档失败')
        })
    }
  }
}
</script>

<style scoped></style>
